import React, { createContext, useState, useContext, ReactNode, useEffect } from 'react';
import { CabinetData, FacilityDevice, DeviceData } from '../types';

// 定义上下文类型
interface AppContextType {
  // 状态
  isLoading: boolean;
  selectedDevice: (CabinetData | FacilityDevice | null);
  viewMode: '2d' | '3d';
  data: {
    cabinets: CabinetData[];
    facilities: FacilityDevice[];
  };
  alerts: {
    id: string;
    message: string;
    type: 'success' | 'error' | 'warning' | 'info';
    timestamp: number;
  }[];
  isSidebarOpen: boolean;
  activeTab: 'overview' | 'devices' | 'alerts' | 'settings';
  filters: {
    deviceType: string;
    status: string;
  };
  
  // 操作函数
  setIsLoading: (loading: boolean) => void;
  setSelectedDevice: (device: CabinetData | FacilityDevice | null) => void;
  setViewMode: (mode: '2d' | '3d') => void;
  updateData: (data: { cabinets?: CabinetData[], facilities?: FacilityDevice[] }) => void;
  addAlert: (message: string, type: 'success' | 'error' | 'warning' | 'info') => void;
  removeAlert: (id: string) => void;
  toggleSidebar: () => void;
  setActiveTab: (tab: 'overview' | 'devices' | 'alerts' | 'settings') => void;
  updateFilters: (filters: Partial<{ deviceType: string; status: string }>) => void;
  resetFilters: () => void;
}

// 创建上下文
const AppContext = createContext<AppContextType | undefined>(undefined);

// 上下文提供者组件
interface AppProviderProps {
  children: ReactNode;
}

// 生成随机ID的辅助函数
const generateId = () => {
  return Math.random().toString(36).substring(2, 10);
};

// 生成模拟数据的辅助函数
const generateMockData = () => {
  // 模拟机柜数据
  const mockCabinets: CabinetData[] = Array.from({ length: 8 }, (_, index) => ({
    id: `cabinet-${index + 1}`,
    name: `服务器机柜 ${index + 1}`,
    model: 'standard',
    manufacturer: '华为',
    location: `机房A-区域${String.fromCharCode(65 + Math.floor(index / 4))}`,
    totalU: 42,
    usedU: Math.floor(Math.random() * 20) + 10,
    temperature: Math.floor(Math.random() * 15) + 20, // 20-35度
    humidity: Math.floor(Math.random() * 20) + 40, // 40-60%
    powerUsage: Math.floor(Math.random() * 300) + 200, // 200-500W
    status: index % 3 === 0 ? 'warning' : index % 5 === 0 ? 'critical' : 'normal',
    position: {
      x: (index % 4) * 2.5 - 3.75,
      y: 0,
      z: Math.floor(index / 4) * 2.5 - 1.25
    },
    dimensions: {
      width: 1,
      height: 2,
      depth: 1
    },
    devices: [] as DeviceData[],
    floorNumber: 1,
    roomId: 'room-1'
  }));

  // 模拟设施设备数据
  const mockFacilities: FacilityDevice[] = [
    // 环境传感器
    { 
      id: 'env-sensor-1',
      name: '温度传感器',
      type: 'temperature',
      location: '机房A-左上角',
      status: 'normal',
      value: Math.floor(Math.random() * 15) + 20,
      unit: '°C',
      position: { x: -4, y: 1.5, z: -3 },
      updateInterval: 60000,
      lastUpdated: new Date().toISOString()
    },
    { 
      id: 'env-sensor-2',
      name: '湿度传感器',
      type: 'humidity',
      location: '机房A-右上角',
      status: 'normal',
      value: Math.floor(Math.random() * 20) + 40,
      unit: '%',
      position: { x: 4, y: 1.5, z: -3 },
      updateInterval: 60000,
      lastUpdated: new Date().toISOString()
    },
    { 
      id: 'env-sensor-3',
      name: '烟雾传感器',
      type: 'smoke',
      location: '机房A-左下角',
      status: 'normal',
      value: 0,
      unit: 'ppm',
      position: { x: -4, y: 1.5, z: 3 },
      updateInterval: 30000,
      lastUpdated: new Date().toISOString()
    },
    // 电力设备
    { 
      id: 'power-device-1',
      name: 'PDU 1',
      type: 'PDU',
      location: '机房A-电力区',
      status: 'online',
      inputVoltage: 220,
      outputVoltage: 220,
      current: 5.5,
      powerRating: 1500,
      efficiency: 95,
      position: { x: -5, y: 0.5, z: 0 }
    },
    { 
      id: 'power-device-2',
      name: 'UPS 1',
      type: 'UPS',
      location: '机房A-电力区',
      status: 'warning',
      inputVoltage: 220,
      outputVoltage: 220,
      current: 3.6,
      powerRating: 1000,
      efficiency: 92,
      batteryLevel: 75,
      position: { x: -6, y: 0.5, z: 0 }
    },
    // HVAC设备
    { 
      id: 'hvac-1',
      name: '空调 1',
      type: 'AC',
      location: '机房A-空调区',
      status: 'online',
      temperatureSetting: 18,
      fanSpeed: 75,
      energyConsumption: 1500,
      position: { x: 0, y: 1.5, z: 4 }
    },
    { 
      id: 'hvac-2',
      name: '通风系统',
      type: 'Ventilation',
      location: '机房A-通风区',
      status: 'online',
      temperatureSetting: 22,
      fanSpeed: 60,
      energyConsumption: 300,
      position: { x: 0, y: 1.5, z: -4 }
    },
    // 消防设备
    { 
      id: 'fire-1',
      name: '喷淋系统',
      type: 'Sprinkler',
      location: '机房A-天花板中央',
      status: 'normal',
      batteryLevel: 100,
      testDate: new Date().toISOString(),
      position: { x: 0, y: 3, z: 0 }
    },
    { 
      id: 'fire-2',
      name: '灭火器',
      type: 'Extinguisher',
      location: '机房A-右侧',
      status: 'normal',
      batteryLevel: 100,
      testDate: new Date().toISOString(),
      position: { x: 5, y: 0.5, z: 0 }
    },
    { 
      id: 'fire-3',
      name: '警报器',
      type: 'Alarm',
      location: '机房A-右侧天花板',
      status: 'normal',
      batteryLevel: 95,
      testDate: new Date().toISOString(),
      position: { x: 4, y: 1.5, z: 3 }
    }
  ];

  return { cabinets: mockCabinets, facilities: mockFacilities };
};

// 上下文提供者组件实现
export const AppProvider: React.FC<AppProviderProps> = ({ children }) => {
  // 状态定义
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [selectedDevice, setSelectedDevice] = useState<CabinetData | FacilityDevice | null>(null);
  const [viewMode, setViewMode] = useState<'2d' | '3d'>('3d');
  const [data, setData] = useState({ cabinets: [] as CabinetData[], facilities: [] as FacilityDevice[] });
  const [alerts, setAlerts] = useState<AppContextType['alerts']>([]);
  const [isSidebarOpen, setIsSidebarOpen] = useState<boolean>(true);
  const [activeTab, setActiveTab] = useState<'overview' | 'devices' | 'alerts' | 'settings'>('overview');
  const [filters, setFilters] = useState<AppContextType['filters']>({
    deviceType: '',
    status: ''
  });

  // 初始化数据
  useEffect(() => {
    const mockData = generateMockData();
    setData(mockData);

    // 添加一些模拟的警报数据，让界面效果更明显
    const mockAlerts = [
      {
        id: generateId(),
        message: '服务器机架A1的温度超过阈值',
        type: 'warning' as const,
        timestamp: Date.now() - 60000 // 1分钟前
      },
      {
        id: generateId(),
        message: 'UPS系统电池电量低于20%',
        type: 'error' as const,
        timestamp: Date.now() - 120000 // 2分钟前
      },
      {
        id: generateId(),
        message: '空调系统已成功启动',
        type: 'success' as const,
        timestamp: Date.now() - 180000 // 3分钟前
      },
      {
        id: generateId(),
        message: '新的固件更新已可用',
        type: 'info' as const,
        timestamp: Date.now() - 300000 // 5分钟前
      },
      {
        id: generateId(),
        message: '湿度传感器需要校准',
        type: 'warning' as const,
        timestamp: Date.now() - 360000 // 6分钟前
      }
    ];
    
    setAlerts(mockAlerts);
  }, []);

  // 添加警报
  const addAlert = (message: string, type: 'success' | 'error' | 'warning' | 'info') => {
    const newAlert = {
      id: generateId(),
      message,
      type,
      timestamp: Date.now()
    };

    setAlerts(prevAlerts => [...prevAlerts, newAlert]);

    // 自动移除警报（3秒后）
    setTimeout(() => {
      removeAlert(newAlert.id);
    }, 3000);
  };

  // 移除警报
  const removeAlert = (id: string) => {
    setAlerts(prevAlerts => prevAlerts.filter(alert => alert.id !== id));
  };

  // 更新数据
  const updateData = (newData: { cabinets?: CabinetData[], facilities?: FacilityDevice[] }) => {
    setData(prevData => ({
      cabinets: newData.cabinets || prevData.cabinets,
      facilities: newData.facilities || prevData.facilities
    }));
  };

  // 切换侧边栏
  const toggleSidebar = () => {
    setIsSidebarOpen(prev => !prev);
  };

  // 更新过滤器
  const updateFilters = (newFilters: Partial<{ deviceType: string; status: string }>) => {
    setFilters(prevFilters => ({ ...prevFilters, ...newFilters }));
  };

  // 重置过滤器
  const resetFilters = () => {
    setFilters({ deviceType: '', status: '' });
  };

  // 上下文值
  const contextValue: AppContextType = {
    isLoading,
    selectedDevice,
    viewMode,
    data,
    alerts,
    isSidebarOpen,
    activeTab,
    filters,
    
    setIsLoading,
    setSelectedDevice,
    setViewMode,
    updateData,
    addAlert,
    removeAlert,
    toggleSidebar,
    setActiveTab,
    updateFilters,
    resetFilters
  };

  return (
    <AppContext.Provider value={contextValue}>
      {children}
    </AppContext.Provider>
  );
};

// 自定义Hook用于使用上下文
export const useApp = (): AppContextType => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
};

// 为了兼容之前的代码，导出一个别名
export const useAppContext = useApp;

// 导出上下文
export default AppContext;